/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.animation.interaction;

import com.bytedance.scene.Scene;
import com.bytedance.scene.animation.TransitionUtils;
import com.bytedance.scene.animation.interaction.progressanimation.InteractionAnimation;
import com.bytedance.scene.navigation.NavigationScene;
import com.bytedance.scene.utlity.CancellationSignal;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorGroup;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by JiangQi on 8/9/18.
 */
public abstract class InteractionNavigationPopAnimationFactory {
    public interface InteractionCallback {
        void onStart();

        void onProgress(float progress);

        void onFinish();
    }

    private NavigationScene mNavigationScene;
    private List<InteractionAnimation> mAnimationList;
    private boolean mStart = false;
    private float mProgress;

    private Scene mToScene;

    private int mToScreenViewVisibility;

    private InteractionCallback mCallback;

    private CancellationSignal mCancellationSignal;
    private static CancellationSignal sCancellationSignal;

    public static void cancelAllRunningInteractionAnimation() {
        if (sCancellationSignal != null) {
            sCancellationSignal.cancel();
            sCancellationSignal = null;
        }
    }

    public void setCallback(InteractionCallback callback) {
        this.mCallback = callback;
    }

    private class CallbackProgressProxyInteractionAnimation extends InteractionAnimation {
        private CallbackProgressProxyInteractionAnimation(float endProgress) {
            super(endProgress);
        }

        @Override
        public void onProgress(float progress) {
            if (mCallback != null) {
                mCallback.onProgress(progress);
            }
        }
    }

    public void begin(NavigationScene navigationScene, Scene from, Scene to) {
        this.mStart = true;
        this.mNavigationScene = navigationScene;
        this.mToScene = to;
        this.mAnimationList = onPopInteraction(from, to);

        if (mCallback != null) {
            this.mAnimationList.add(new CallbackProgressProxyInteractionAnimation(1.0f));
        }

        this.mToScreenViewVisibility = this.mToScene.getView().getVisibility();
        this.mToScene.getView().setVisibility(Component.VISIBLE);

        mCancellationSignal = new CancellationSignal();
        mCancellationSignal.setOnCancelListener(this::forceCancel);
        setCancellationSignal(mCancellationSignal);

        if (this.mCallback != null) {
            this.mCallback.onStart();
        }
    }

    private static void setCancellationSignal(CancellationSignal mCancellationSignal){
        sCancellationSignal = mCancellationSignal;
    }

    public void finish() {
        if (!this.mStart) {
            return;
        }
        this.mStart = false;

        float progress = this.mProgress;
        this.mProgress = 0;

        final boolean canExit = canExit(progress);
        List<Animator> animatorList = new ArrayList<>();
        for (InteractionAnimation animation : mAnimationList) {
            AnimatorValue animatorValue = new AnimatorValue();
            animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                float currentProgress = animation.getCurrentProgress();

                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    if (canExit) {
                        currentProgress += 0.05;
                        if (currentProgress > 1) {
                            currentProgress = 1f;
                        }
                    } else {
                        currentProgress -= 0.05;
                        if (currentProgress < 0) {
                            currentProgress = 0f;
                        }
                    }
                    animation.dispatchProgress(currentProgress);
                }
            });
            animatorValue.setDuration(150);
            animatorList.add(animatorValue);
        }

        final Animator animator = TransitionUtils.mergeAnimators(animatorList);

        ((AnimatorGroup) animator).setStateChangedListener(new Animator.StateChangedListener() {
            boolean isCanceled = false;

            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {
                isCanceled = true;
            }

            @Override
            public void onEnd(Animator animator) {
                if (canExit && !isCanceled) {
                    popWithoutAnimation();
                } else {
                    restoreStatusNow();
                }
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        ((AnimatorGroup) animator).setCurveType(Animator.CurveType.CUBIC_BEZIER_EXTREME_DECELERATION);
        animator.start();
        mAnimationList = null;

        mCancellationSignal.setOnCancelListener(animator::cancel);
    }

    private void resetCancellationSignal() {
        if (sCancellationSignal == mCancellationSignal) {
            sCancellationSignal = null;
        }
    }

    private void popWithoutAnimation() {
        resetCancellationSignal();
        mNavigationScene.convertBackgroundToDefault();
        onInteractionEnd();
        if (this.mCallback != null) {
            this.mCallback.onFinish();
        }
    }

    public void forceCancel() {
        if (!this.mStart) {
            return;
        }
        updateProgress(0.0f);
        this.mStart = false;
        restoreStatusNow();
    }

    private void restoreStatusNow() {
        resetCancellationSignal();
        mNavigationScene.convertBackgroundToDefault();
        mToScene.getView().setVisibility(mToScreenViewVisibility);
        onInteractionCancel();

        if (this.mCallback != null) {
            this.mCallback.onFinish();
        }
    }

    protected abstract boolean canExit(float progress);

    protected abstract void onInteractionCancel();

    protected abstract void onInteractionEnd();

    public abstract boolean isSupport(Scene from, Scene to);

    protected abstract List<InteractionAnimation> onPopInteraction(Scene from, Scene to);

    public void updateProgress(float progress) {
        if (!this.mStart) {
            return;
        }

        for (InteractionAnimation animation : mAnimationList) {
            animation.dispatchProgress(progress);
        }
        this.mProgress = progress;
    }
}
